package com.qfedu.edu.seckill.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author xiaobobo
 * @title: MyFeignRequestInterceptor
 * @projectName cd-java-2404-seckill-parent
 * @description: 这个拦截器的主要功能是实现Feign的级联传输
 * @date 2025/1/13  14:38
 */
@Component
public class MyFeignRequestInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        //首先要找到 原始请求...
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        //将上传的请求属性集转换成和Servlet相关的对象
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
        //通过属性集拿到原始的请求对象
        HttpServletRequest request = servletRequestAttributes.getRequest();
        //找到传输的token对象
        String token = request.getHeader("token");
        //如果是服务之间的调用传输那么 还需要将这个网关标记给传输过去
        requestTemplate.header("gatewayTag","gatewayTag");
        //接下来将这个token放到新的请求中去
        requestTemplate.header("token", token);
    }
}
